<template>
  <div class="process_template">
    <el-dialog
      title="参数记录表详情"
      :visible.sync="dialogVisible"
      width="1200px"
      v-dialogDrag
      :close-on-click-modal="false"
      @closed="close"
      customClass="mes_dialog">
      <div class="detail_wrapper" v-loading="isLoading">
        <div class="detail_header">
          <div class="header_left">
            <span class="template_label"><i class="label_star">*</i>模板名称：</span>
            <div class="template_name">
              <el-input size="small" placeHolder="请输入模板名称"
                        v-model.trim="workStageInfo.templateName"></el-input>
            </div>
            <span class="random_btn">
              <el-tooltip effect="dark"
                          content="随机生成模板名称"
                          placement="bottom">
                <i class="iconfont icon-random" @click="randomTemplateName"></i>
              </el-tooltip>
            </span>
            <span class="template_label"><i class="label_star">*</i>密级选择：</span>
            <el-select v-model="workStageInfo.secretLevelId" size="small" placeholder="请选择密级">
              <el-option
                v-for="item in personSecretLevel"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="header_right">
            <div class="template_item">物料名称：<span>{{workStageInfo.materialName}}</span></div>
            <div class="template_item">工序名称：<span>{{workStageInfo.workstageName}}</span></div>
          </div>
        </div>
        <div class="detail_cont">
          <div class="table_label_title table_item">
            <div class="label_index"></div>
            <div class="label_project">参数项目</div>
            <div class="label_type">类型</div>
            <div class="label_val">选择值</div>
            <div class="label_lower_limit">参考下限</div>
            <div class="label_upper_limit">参考上限</div>
            <div class="label_unit">计量单位</div>
            <div class="label_handle">操作</div>
          </div>
          <div class="table_body" :style="{height: maxHeight}" v-if="dialogVisible">
            <el-scrollbar>
              <draggable element="div"
                         class="drag_cont"
                         v-model="workStageInfo.templateList"
                         :options="dragOptions">
                <transition-group type="transition" :name="'flip-list'">
                  <div class="table_item" :key="`${$index}`" v-for="(item, $index) in workStageInfo.templateList">
                    <div class="label_index">
                      <el-tooltip effect="dark"
                                  content="可拖动"
                                  :open-delay="300"
                                  :disabled="isEdit !== null"
                                  placement="bottom">
                        <span class="iconfont icon-drag"></span>
                      </el-tooltip>
                      <span class="drag_number">{{$index >= 9 ? '' : 0}}{{$index + 1}}</span>
                    </div>
                    <div class="label_project">
                      <el-input v-if="isEdit === $index"
                                maxlength="12"
                                clearable
                                placeholder="请输入参数项目名称"
                                v-model.trim="item.name" size="mini"></el-input>
                      <tooltip-txt v-else :text="item.name"></tooltip-txt>
                    </div>
                    <div class="label_type">
                      <el-select v-if="isEdit === $index" v-model="item.typeValue"
                                 placeholder="请选择"
                                 size="mini">
                        <el-option
                          v-for="item1 in TemplateValueType"
                          :key="item1.value"
                          :label="item1.label"
                          :value="item1.value">
                        </el-option>
                      </el-select>
                      <tooltip-txt v-else :text="item.typeLabel"></tooltip-txt>
                    </div>
                    <div class="label_val">
                      <div class="input_cont" v-if="item.typeValue === 'Selection'">
                        <el-input v-if="isEdit === $index"
                                  clearable
                                  placeholder="请输入选项值，已逗号分隔"
                                  v-model.trim="item.selections" size="mini"></el-input>
                        <tooltip-txt v-else :text="item.selections"></tooltip-txt>
                      </div>
                      <span class="disabled_item" v-else>-</span>
                    </div>
                    <div class="label_lower_limit">
                      <div class="input_cont"
                           v-if="item.typeValue === 'Number'">
                        <el-input v-if="isEdit === $index"
                                  clearable
                                  placeholder="请输入"
                                  v-model.trim="item.lowerLimit" size="mini"></el-input>
                        <!--<el-input-number-->
                          <!--v-if="isEdit === $index"-->
                          <!--size="mini"-->
                          <!--v-model="item.lowerLimit"-->
                          <!--:controls="false"-->
                          <!--:precision="3"-->
                          <!--placeholder="请输入"></el-input-number>-->
                        <tooltip-txt v-else :text="(item.lowerLimit || '') + ''"></tooltip-txt>
                      </div>
                      <div class="disabled_item" v-else>-</div>
                    </div>
                    <div class="label_upper_limit">
                      <div class="input_cont"
                           v-if="item.typeValue === 'Number'">
                        <el-input v-if="isEdit === $index"
                                  clearable
                                  placeholder="请输入"
                                  v-model.trim="item.upperLimit" size="mini"></el-input>
                        <!--<el-input-number-->
                          <!--v-if="isEdit === $index"-->
                          <!--size="mini"-->
                          <!--v-model="item.upperLimit"-->
                          <!--:controls="false"-->
                          <!--:precision="3"-->
                          <!--placeholder="请输入"></el-input-number>-->
                        <tooltip-txt v-else :text="(item.upperLimit || '') + ''"></tooltip-txt>
                      </div>
                      <div class="disabled_item" v-else>-</div>
                    </div>
                    <div class="label_unit">
                      <div class="input_cont">
                        <el-select v-if="isEdit === $index" v-model="item.unitValue"
                                   placeholder="请选择"
                                   size="mini">
                          <el-option
                            v-for="item1 in ParameterUnitType"
                            :key="item1.value"
                            :label="item1.label"
                            :value="item1.value">
                          </el-option>
                        </el-select>
                        <tooltip-txt v-else :text="item.unitLabel"></tooltip-txt>
                      </div>
                    </div>
                    <div class="label_handle icon_btn">
                      <i v-if="isEdit === $index" @click="verifyItem" class="iconfont icon-td_finish1"></i>
                      <i v-if="isEdit !== $index" @click="_edit($index)" class="iconfont icon-btn_edit"></i>
                      <i v-if="isEdit !== $index" @click="_add($index)" class="iconfont icon-td_add2"></i>
                      <i @click="_delete($index)" class="iconfont icon-btn_delete"></i>
                    </div>
                  </div>
                </transition-group>
              </draggable>
            </el-scrollbar>
          </div>
        </div>
      </div>
      <span slot="footer" class="mes_btn">
        <el-button type="primary" @click="save">提交</el-button>
        <el-button @click="this.close">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'

export default {
  name: 'ProcessTemplate',
  data() {
    return {
      // 模板信息
      workStageInfo: {},
      // 显示弹框
      dialogVisible: false,
      // 数据加载中
      isLoading: false,
      // 是否修改过
      isEditState: false,
      // 是否保存中
      saveState: false,
      // 模板密级
      secrecyGrade: '',
      // 是否编辑中
      isEdit: null, // 是否编辑中
    }
  },
  components: {
    Draggable,
  },
  computed: {
    // 拖拽配置
    dragOptions() {
      return {
        animation: 0,
        group: 'description',
        ghostClass: 'ghost',
        disabled: this.isEdit !== null
      }
    },
    // 人员保密级别
    personSecretLevel() {
      return this.$store.state.dict.personSecretLevel.labels || []
    },
    // 模板数据类型
    TemplateValueType() {
      return this.$store.state.dict.TemplateValueType.labels || []
    },
    // 模板数据单位
    ParameterUnitType() {
      return this.$store.state.dict.ParameterUnitType.labels || []
    },
    maxHeight() {
      if (!this.workStageInfo.templateList) {
        return '0px'
      } else if (this.workStageInfo.templateList.length < 10) {
        return this.workStageInfo.templateList.length * 40 + 'px'
      }
      return '400px'
    }
  },
  watch: {
    workStageInfo: {
      handler(now, old) {
        if (Object.keys(old).length) {
          this.isEditState = true
        }
      },
      deep: true
    }
  },
  created() {
  },
  methods: {
    /**
     * 打开方法
     * @param obj
     * materialName: String，必传，物料名称
     * workstageName: String，必传，工序名称
     * entry: String，必传，工序类型(工单工序：'workorder',批次工序：'batch')
     * workstageId: String，必传，工序ID
     * isNew: Boolean，必传，是否新增模板
     */
    openDialog(obj) {
      obj.templateList = [{}]
      obj.templateName = ''
      obj.secretLevelId = ''
      this.dialogVisible = true
      // 判断是否为新增
      if (obj.isNew) {
        // 模板信息
        this.workStageInfo = obj
        this.randomTemplateName()
        this.isEdit = 0
      } else {
        this.isLoading = true
        this.getTemplate(obj)
      }
    },
    // 随机生成模板名称
    randomTemplateName() {
      this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/generatetemplatename/' + this.workStageInfo.workstageNumber,
        noCommit: true
      }).then(res => {
        if (res.data.templateName) this.workStageInfo.templateName = res.data.templateName
      })
    },
    // 获取模板
    getTemplate(obj) {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/retrieveparamtemplate',
        data: {
          workstageId: obj.workstageId,
          entry: obj.entry
        },
        noCommit: true
      }).then(res => {
        if (res.data.inventory) {
          obj.templateList = JSON.parse(res.data.inventory)
          obj.templateList = obj.templateList.map(item => this.addLabel(item))
        }
        if (res.data.name) obj.templateName = res.data.name
        if (res.data.secretLevelId) obj.secretLevelId = res.data.secretLevelId
        this.workStageInfo = obj
        this.isEdit = null
        this.isLoading = false
      }).catch(() => {
        this.workStageInfo = obj
        this.isEdit = 0
        this.isLoading = false
      })
    },
    // 编辑
    _edit(index) {
      // 非编辑状态可以编辑
      if (this.isEdit === null) {
        this.isEdit = index
      } else {
        this.$message({
          type: 'error',
          message: '请先保存当前编辑的数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 添加
    _add(index) {
      // 非编辑状态可以添加
      if (this.isEdit === null) {
        this.workStageInfo.templateList.splice(index + 1, 0, {})
        this.isEdit = index + 1
      } else {
        this.$message({
          type: 'error',
          message: '请先保存当前编辑的数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 删除
    _delete(index) {
      // 非编辑状态可以删除，编辑状态只能删除当前编辑的那一项
      if (this.isEdit === null || this.isEdit === index) {
        if (this.workStageInfo.templateList && this.workStageInfo.templateList.length > 1) {
          this.workStageInfo.templateList.splice(index, 1)
          this.isEdit = null
        } else {
          this.workStageInfo.templateList = [{}]
          this.isEdit = 0
        }
      } else {
        this.$message({
          type: 'error',
          message: '请先保存当前编辑的数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 验证当前编辑项
    verifyItem() {
      let rowItem = this.workStageInfo.templateList[this.isEdit]
      if (!rowItem.name) {
        this.$message({
          type: 'error',
          message: '请填写参数项目名称',
          duration: 1500,
          center: true
        })
      } else if (this.workStageInfo.templateList.some((item, index) => item.name === rowItem.name && index !== this.isEdit)) {
        this.$message({
          type: 'error',
          message: '模板中的参数项目名称不能重复',
          duration: 1500,
          center: true
        })
      } else if (!rowItem.typeValue) {
        this.$message({
          type: 'error',
          message: '请选择类型',
          duration: 1500,
          center: true
        })
      } else {
        switch (rowItem.typeValue) {
          case 'Selection':
            if (!rowItem.selections) {
              this.$message({
                type: 'error',
                message: '请填写选项值',
                duration: 1500,
                center: true
              })
            } else {
              // 将选项值里面的逗号都替换为英文逗号
              rowItem.selections = rowItem.selections.replace(/，/ig, ',')
              return this.saveItem(rowItem)
            }
            break
          // case 'Number':
          //   if (Number(rowItem.upperLimit) < Number(rowItem.lowerLimit) && rowItem.upperLimit.length && rowItem.lowerLimit.length) {
          //     this.$message({
          //       type: 'error',
          //       message: '参考下限不能大于参考上限',
          //       duration: 1500,
          //       center: true
          //     })
          //   } else {
          //     return this.saveItem(rowItem)
          //   }
          //   break
          default:
            return this.saveItem(rowItem)
        }
      }
    },
    // 保存当前编辑项
    saveItem(rowItem) {
      let obj = this.addLabel(rowItem)
      Object.assign(this.workStageInfo.templateList[this.isEdit], obj)
      this.isEdit = null
      return true
    },
    // 增加value 和 label
    addLabel(row) {
      // 获取当前类型字典项
      let obj = {}
      if (row.type || row.typeValue) {
        let type = this.TemplateValueType.find(item => item.value === row.typeValue || item.id === row.type) || {}
        obj.type = type.id
        obj.typeLabel = type.label
        obj.typeValue = type.value
      }
      if (row.unit || row.unitValue) {
        let unit = this.ParameterUnitType.find(item => item.value === row.unitValue || item.id === row.unit) || {}
        obj.unit = unit.id
        obj.unitLabel = unit.label
        obj.unitValue = unit.value
      }
      return Object.assign(row, obj)
    },
    // 保存
    save() {
      if (this.saveState === true) return
      if (!this.workStageInfo.templateName) {
        this.$message({
          type: 'error',
          message: '请填写模板名称',
          duration: 1500,
          center: true
        })
      } else if (!this.workStageInfo.secretLevelId) {
        this.$message({
          type: 'error',
          message: '请选择密级',
          duration: 1500,
          center: true
        })
      } else if (!this.isEditState) {
        this.close()
      } else if (this.isEdit === null || this.verifyItem() === true) {
        /* 非编辑状态 或者 编辑行保存成功执行 */
        this.submit()
      }
    },
    // 提交
    submit() {
      let templateList = this.workStageInfo.templateList.map(item => {
        let obj = Object.assign({}, item)
        delete obj.typeLabel
        delete obj.typeValue
        delete obj.unitLabel
        delete obj.unitValue
        return obj
      })
      let postData = {
        entry: this.workStageInfo.entry,
        name: this.workStageInfo.templateName,
        secretLevelId: this.workStageInfo.secretLevelId,
        workstageId: this.workStageInfo.workstageId,
        inventory: JSON.stringify(templateList)
      }
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/saveparamtemplate',
        data: postData,
        noCommit: true
      }).then(() => {
        this.close()
        this.$emit('success')
        this.$message.success({
          message: '保存成功',
          duration: 1500,
          center: true
        })
      })
    },
    // 关闭并清空
    close() {
      this.dialogVisible = false
      this.workStageInfo = {}
      this.isEditState = false
      this.saveState = false
    }
  }
}
</script>
<style lang="less">
  .process_template .el-input-number {
    width: 100%;
    .el-input__inner{
      text-align: left;
    }
  }
</style>
<style scoped lang="less">
  .process_template{
    .detail_header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      padding-bottom: 20px;
      .header_left {
        display: flex;
        align-items: center;
        padding-right: 20px;
        box-sizing: border-box;
        .template_label {
          flex: 0 0 80px;
          font-size: 14px;
          color: #333;
          white-space: nowrap;
          .label_star {
            font-style: normal;
            color: #f8000f;
          }
        }
        .template_name{
          flex: 0 0 240px;
        }
        .random_btn{
          margin-left: 10px;
          color: #00b4ff;
          cursor: pointer;
          margin-right: 50px;
          padding-top: 1px;
          .icon-random{
            font-size: 24px;
          }
        }
      }
      .header_right{
        display: flex;
        .template_item {
          box-sizing: border-box;
          text-align: right;
          &:last-child{
            padding-left: 50px;
          }
        }
      }
    }
    .detail_cont {
      border: 1px solid #dbe1e8;
      .flip-list-move {
        transition: transform 0.5s;
      }
      .no-move {
        transition: transform 0s;
      }
      .ghost {
        opacity: .5;
        background: #C8EBFB;
      }
      .table_item {
        display: flex;
        height: 40px;
        line-height: 40px;
        box-sizing: border-box;
        border-bottom: 1px solid #dbe1e8;
        text-align: center;
        font-size: 14px;
        color: #333;
        background-color: #fff;
        overflow: hidden;
        &:last-child {
          border-bottom: 0;
        }
        .label_index {
          flex: 0 0 80px;
          box-sizing: border-box;
          padding: 0 10px;
          display: flex;
          border-right: 1px solid #dbe1e8;
          cursor: pointer;
          overflow: hidden;
          .iconfont {
            flex: 0 0 30px;
          }
          .drag_number {
            flex: 0 0 30px;
          }
        }
        .label_project {
          flex: 0 0 200px;
          box-sizing: border-box;
          padding: 0 10px;
          border-right: 1px solid #dbe1e8;
          overflow: hidden;
        }
        .label_type {
          flex: 0 0 120px;
          box-sizing: border-box;
          padding: 0 10px;
          border-right: 1px solid #dbe1e8;
          overflow: hidden;
        }
        .label_val {
          flex: 0 0 308px;
          box-sizing: border-box;
          border-right: 1px solid #dbe1e8;
          overflow: hidden;
        }
        .label_upper_limit {
          flex: 0 0 120px;
          box-sizing: border-box;
          border-right: 1px solid #dbe1e8;
          overflow: hidden;
        }
        .label_lower_limit {
          flex: 0 0 120px;
          box-sizing: border-box;
          border-right: 1px solid #dbe1e8;
          overflow: hidden;
        }
        .label_unit {
          flex: 0 0 110px;
          box-sizing: border-box;
          border-right: 1px solid #dbe1e8;
          overflow: hidden;
        }
        .label_handle {
          flex: 0 0 100px;
          box-sizing: border-box;
        }
        .icon_btn {
          padding-left: calc((100px - 72px)/2);
          padding-right: 10px;
          display: flex;
          flex-wrap: wrap;
          justify-content: flex-start;
          .iconfont {
            font-size: 14px;
            cursor: pointer;
          }
          .icon-btn_edit {
            color: #00b4ff;
            margin-right: 15px;
          }
          .icon-td_add2, .icon-td_finish1 {
            color: #3c6;
          }
          .icon-btn_delete {
            color: #7e8e9f;
            margin-left: 15px;
          }
        }
        .input_cont{
          padding: 0 10px;
        }
        .disabled_item {
          display: block;
          height: 100%;
          width: 100%;
          background-color: #f5f7fa;
          font-size: 30px;
          padding: 0 10px;
          box-sizing: border-box;
        }
      }
      .table_label_title {
        background-color: #ebf0f6;
        box-sizing: border-box;
        color: #000;
        font-weight: bold;
      }
      .table_body{
        .el-scrollbar {
          height: 100%;
        }
      }
      .drag_cont{
        .label_project {
          overflow: hidden;
          text-align: left;
        }
        .label_val {
          overflow: hidden;
          .input_cont{
            text-align: left;
          }
        }
      }
    }
  }
</style>
